package com.fuluwa.interfaces.file.facade;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.fuluwa.domain.file.model.FileInfo;
import com.fuluwa.infra.consts.FileConsts;
import com.fuluwa.infra.exception.PersistenceException;
import com.fuluwa.infra.jms.MessageProducer;
import com.fuluwa.interfaces.security.web.UserController;

@Component
public class FileServiceFacadeImpl implements FileServiceFacade {
	protected final static Logger logger = LoggerFactory.getLogger(FileServiceFacadeImpl.class);
	@Autowired
	MessageProducer messageProducer;

	@Transactional
	public Long saveFile(MultipartFile file) throws PersistenceException, IOException {
		String filename = file.getOriginalFilename();
		logger.debug("uploading file:" + filename);
		FileInfo fileInfo = new FileInfo(filename, filename);
		fileInfo.save();
		// file name add timestamp
		filename = FileConsts.FILE_OUTPUT_PATH + fileInfo.getId() + "_" + filename;
		fileInfo.updatePhiscalPath(filename);

		logger.debug("uploading file has been writen to:" + filename);

		File source = new File(filename);
		file.transferTo(source);

//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("fileInfoId", fileInfo.getId());

//		messageProducer.sendFileUploadQueue(map);

		return fileInfo.getId();
	}

	@Override
	@Transactional
	public String readFile(Long id) throws PersistenceException, IOException {
		FileInfo fileInfo = new FileInfo(id);
		fileInfo = fileInfo.load();
		return FileUtils.readFileToString(new File(fileInfo.getPhiscalPath()));
	}
}
